07. String Manipulation Quiz 1 Solution

JavaScript's String .slice() Method

To solve this quiz, we'll need the help of JavaScript's .slice() method. The slice method copies a portion of the original string and returns it. The slice method takes two arguments:

  1. the position to start copying
  2. the position to stop copying
stringToCopy.slice(beginPosition [, optionalEndPosition])

Let's check out a few examples:

var copiedText = 'JavaScript is powerful!'.slice(0, 19);
console.log(copiedText);

Logs: 'JavaScript is power'

In the code above, the slice method uses the values 0 and 19. This copies the string from the first character (which is at the 0th position!) all the way up to, but not including, the 19th character:

J  a  v  a  S  c  r  i  p  t    i  s     p  o  w  e  r
0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18

In this next example, slice() starts at the 14th character and stops at the 56th:

var copiedText2 = 'JavaScript is prototype-based with first-class functions, making it a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles.'.slice(14, 56);
console.log(copiedText2);

Logs: 'prototype-based with first-class functions'

The ending position is optional. If we don't supply an ending position, then the string will be copied from the start of the string all the way to the end of the string.

var copiedText3 = 'Almost everyone loves ice cream!'.slice(7);
console.log(copiedText3);

Logs: 'everyone loves ice cream!'

Quiz Solution

Now that we know how .slice() works, we can use it to solve the quiz.

Since audacity has most of Udacity in it, we can use .slice() to copy out the portion we need.

var copiedText = 'audacity'.slice(2);
console.log(copiedText);

Logs: 'dacity'

And then we can just add the U manually:

var udacityText = 'U' + copiedText';
console.log(udacityText);

Logs: 'Udacity'

We've got the string "Udacity"! So the solution to the quiz is:

var udacityizer = function(string) {  
    string = 'U' + string.slice(2);
    return string;
};